package com.adv.netWork01.downloadServer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class DownloadServer extends Thread {
//按自己思路写的，结果测试不对……
	private ServerSocket s;
	static byte[] b;

	public DownloadServer(ServerSocket s) {
		this.s = s;
		super.setName(String.valueOf(s.getInetAddress()));

	}

	// 寻找文件
	public static void findFile(File dir, List<File> result) {// 网上百度的方法
		File[] files = dir.listFiles();
		if (files != null) {
			for (File file : files) {
				if (file.isDirectory()) {
					// 递归目录
					findFile(file, result);
				} else {
					// 判断后缀,这里可以加入其他判断
					if (file.getName().equals(dir.getName())) {
						result.add(file);
					}
				}
			}
		}

	}

	@Override
	public void run() {
		System.out.println("-------服务器-------");
		try {
			Socket client = s.accept();
			System.out.println(s.getInetAddress() + ":" + client.getPort() + "连接上了...");
			OutputStream out = client.getOutputStream();
			PrintWriter pw = new PrintWriter(out);// 写出 问要查哪个文件
			InputStream is = client.getInputStream();// 读入要查的文件名
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			pw.println("请输入要查询的文件全名：");
			pw.flush();
			String file = br.readLine();// 要查的文件名
			System.out.println("客户端<" + s.getInetAddress() + ">说：" + file);
			// 查找文件
			File dir = new File("/file");
			List<File> result = new ArrayList<File>();
			findFile(dir, result);
			System.out.println(result);
			file = result.get(0).toString();
			File f = new File(file);
			FileInputStream fin = new FileInputStream(f.getAbsolutePath() + file);// 重新给读入的文件名
			b = new byte[fin.available()];
			fin.read(b);
			fin.close();
			out.write(b);
			out.flush();
			System.out.println("文件发送给" + s.getInetAddress() + "成功");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (s != null)
				try {
					s.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

	public static void main(String[] args) throws Exception {
		DownloadServer dls = new DownloadServer(new ServerSocket(9999));
		dls.start();
	}
}
